var appPath = getAppPath();	


//  初始化加载 数据
$(function(){
	// 检索日期范围
	$("#queryDateStart").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	$("#queryDateEnd").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	
	var data = [{'id':'0','name':'[不限]'},{'id':'10','name':'未开始'},
	            {'id':'20','name':'进行中'},{'id':'30','name':'已结束'}];
	$("#queryNotifyState").combobox({
		data : data,
		valueField : 'id',
		textField : 'name',
		onLoadSuccess :function(){
			$("#queryNotifyState").combobox('select',0).combobox('enable');
		}
	});
	

	initJspGrid();
});

function doSearch() {
    $("#rightGrid").datagrid("load", {
    "sTitle" : $("#sTitle").val()
    });
}

function dtFmt(dt){
	var y = dt.getFullYear();
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);//格式化mm-dd
}
function dtParser(s){
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        return new Date(y,m-1,d);
    } else {
        return new Date();
    }
}

// 列表初始化
function initJspGrid(){
	
	// 初始化 加载 消息管理页面
	$('#tmplGrid').datagrid({
	    url:appPath + "/yjxNotify/getNotifyInfoPg.action",
	    height:'full',
	    striped:true,
	    fitColumns:true,
	    nowrap: false,// 换行
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
			//微缩图
		    {field:'image',title:'缩略图',width:75,align:'center',sortable:false,
	        	formatter:function(thumb, rowData, rowIndex){
	        		var retUrl = '';
					if (thumb) {
						retUrl = '<a href="' + thumb + '" target="_blank">'
							+ '<div style="display:table;text-align:center;height:110px;width:100%">'
							+ '<span style="display:table-cell;vertical-align:middle">'
							+ '<img src="' +thumb+''//?x-oss-process=image/resize,m_lfit,h_120,w_100
							+ '" style="display:inline;max-height:100px;max-width:100px"></span></div></a>';
					}
					return retUrl;
	        	}},
	    		{field:'edit',title:'编辑',width:35,align:'center',sortable:false,
					formatter:function(value,rowData,rowIndex){
						//if(Number(rowData.publish||'0')==1) return "N/A";
						var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' ";
						ret += " onClick='editNotify("+rowData.ntfy_id+")'/></a>";
						return ret;
					}
				},
		        {field:'ntfy_id',title:'ID',width:30,align:'center',sortable:false},
		        {field:'ntfy_type',title:'分类',width:60,align:'center',sortable:false,
			    	  formatter:function(value, rowData, rowIndex){
			    		  var tn = '<span style="color:red">其它</span>';
			    		  switch(Number(value||'0')){
			    		  	case 11: tn ='<span style="color:#CD919E;">APP开机广告</span>';break;
			    		  	case 12: tn ='<span style="color:#CD8162;">APP轮播图</span>';break;
			    		  	case 13: tn ='<span style="color:#CD6839;">APP发现轮播图</span>';break;
			    		  	case 14: tn ='<span style="color:red;">APP弹窗广告</span>';break;
			    		  	case 21: tn ='<span style="color:#CD5C5C;">WEB轮播图</span>';break;
			    		  }
			    		  return tn;
			    	  }
		        },
//		   		{field:'messagedit',title:'发通知',width:40,align:'center',sortable:false,
//					formatter:function(value,rowData,rowIndex){
//						if(Number(rowData.type||'0')!=102) return "№";
//						var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/redo.png' title='指定用户' ";
//						ret += " onClick='editMessage("+rowData.id+")'/></a>";
//						return ret;
//					}
//				},
			    {field:'order',title:'序号',width:30,align:'center',sortable:false,
				   	  formatter:function(value, rowData, rowIndex){
			    		  if(!rowData.ntfy_id) return "";
			    		  return "<a href='javascript:void(0)' onClick='editNotifyOrder("+rowData.ntfy_id+","+rowData.order+")'>"+rowData.order+"</a>";
			    	  }
			    },
			    {field:'title',title:'标题',width:65,align:'center',sortable:false,},
			    {field:'message',title:'消息内容',width:90,align:'left',sortable:false,
			    	  formatter:function(value, rowData, rowIndex){
			    		  if(!rowData.message){
			    			  return 'N/A';
			    		  }
			    		  if(rowData.message&&rowData.message.length>0){
			    			  	if(rowData.message.length>10){
			    			  		return rowData.message.substr(0,15)+'...';			    		
			    			  	}else{
			    			  		return rowData.message;
			    			  	}
			    		  }
			    	  }
			    },
				{field:'url',title:'链接',width:35,align:'center',sortable:false,
					  formatter:function(value, rowData, rowIndex){
					  	if(value){
					  		if(value.indexOf("http")>=0){//看是否加了带http的头消息
					  			return '<a href="'+rowData.url+'" target="_blank"><span style="color:red;">查看</span></a>';
				  			}	
						  	return '<a href="http://'+rowData.url+'" target="_blank"><span style="color:red;">查看</span></a>';
						}else{
							return 'N/A';
						}
			        }
				},
			    {field:'valid',title:'状态',width:40,align:'center',sortable:false,
			    	formatter:function(value, rowData, rowIndex){
			    		var ret = '<span style="color:">未知</span>';
			    		if (value){
			    			switch(value){
			    			case 10: ret = '<span style="color:green;">未开始</span>';break;
			    			case 20: ret = '<span style="color:#EE9A00;">进行中</span>';break;
			    			case 30: ret = '<span style="color:red;">已结束</span>';break;
			    			}
			    		}
			    		return ret;
			    	}
			    },
			    {field:'start_time',title:'有效期开始日时',width:85,align:'center',sortable:false,
			    	formatter:function(value, rowData, rowIndex){
		  		     	if(value){
		  		     		var show = value.substr(0,19);
		  		     		if(rowData.valid==10) {// 未开始
		  		     			show = '<span style="color:green">'+show+'</span>'
		  		     		}
		  		     		return show;
			  		  	}
		        	}
			    },
			    {field:'end_time',title:'有效期截止日时',width:85,align:'center',sortable:false,
			    	formatter:function(value, rowData, rowIndex){
		  		     	if(value){
		  		     		var show = value.substr(0,19);
		  		     		if(rowData.valid==30) {// 过期
		  		     			show = '<span style="color:red">'+show+'</span>'
		  		     		}
		  		     		return show;
			  		  	}
			    	}
			    },
			    {field:'create_time',title:'创建时间',width:55,align:'center',sortable:false},
			    {field:'update_time',title:'修改时间',width:55,align:'center',sortable:false}

	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'添加消息',
			iconCls:'icon-add',
			handler:function(){
				addNotify();
			}
		},
		{
			text:'删除消息',
			iconCls:'icon-cancel',
			handler:function(){
				delNotify();
			}
		}]	
	});
}

//  编辑  notify信息
function editNotify(stId){	
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#topicImg").html('').val('');
	
	$("#trForNew").hide();
	$("#trForEdit").show();
	
	$("#editStId").val(stId);
	var url = appPath + "/yjxNotify/getNotifyInfoLst.action?id="+ stId;//映射专题编辑的信息
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			var type = Number(info.ntfy_type||0);
			
			$("#editTopicTitle").val(info.title||'');
			$("#editTopicDesc").val(info.message||'');
			$("#editTopicUrl").val(info.url||'');
			$("#editNotifyUse").combobox('select',type||'');// 大的分类
			
			$("#editNotifyUse").combobox({
				onBeforeLoad : function(){
					$("#editNotifyUse").combobox('select',type||'');//大的分类
				},
				onSelect : function(ret){
					if (ret.value == 14) {
						$("#editNotifyDisplay").combobox('select',info.disp_type);//可使用的 
						$('#editEmbedUrl').attr('disabled',false);
						$("#editNotifyDisplay").combobox({disabled: false}); 
						$('#editEmbedW').attr('disabled',false);
						$('#editEmbedH').attr('disabled',false);
					} else {
						$("#editNotifyDisplay").combobox('select',0);//可使用的 
						$('#editEmbedUrl').attr('disabled',true);
						$("#editNotifyDisplay").combobox({disabled: true}); 
						$('#editEmbedW').attr('disabled',true);
						$('#editEmbedH').attr('disabled',true);
						$("#editEmbedUrl").val('');
						$("#editEmbedH").val('');
						$("#editEmbedW").val('');
					}
				}
			});
			
			
			$("#editEncrypt").combobox('select',info.encrypt||'0');
			$("#queryDateStartEdit").datebox('setValue',info.start_time||'');
			$("#queryDateEndEdit").datebox('setValue',info.end_time||'');
			$("#editCurType").val(type);
			$("#editTopicChkFreq").val(info.chk_freq||0);
			
			$("#editEmbedUrl").val(info.embed_url||'');
			$("#editEmbedW").val(info.width||'');
			$("#editEmbedH").val(info.height||'');
			
			var showImg = '';
			var imgHtml = '';
	
			if(info.image && info.image.length>0) {
				showImg = info.image.replace('oss-cn-hangzhou.aliyuncs.com','img-cn-hangzhou.aliyuncs.com')
				imgHtml = '<a href='+showImg+' target ="blank"><img src="'+showImg+'?x-oss-process=image/resize,m_pad,h_150,w_150,color_cccccc" style="display:inline;max-height:100px;max-width:200px"></a>';
			}
			$("#topicImg").append(imgHtml).val(info.image||'');
		}
	});
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'编辑消息',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	cancelPostData();// 上传图片清除 uploader = null
	initOSS();
	
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}

//	添加消息内容
function addNotify(){
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#topicImg").html('').val('');
	
	$("#trForNew").show();
	$("#trForEdit").hide();
	
//	$("#editNotifyUse").combobox('select',12).combobox('enable');//可使用的 
	$("#editNotifyUse").combobox({
		onBeforeLoad : function(){
			$("#editNotifyUse").combobox('select',12).combobox('enable');//可使用的 
		},
		onSelect : function(ret){
			if (ret.value == 14){
				$("#editNotifyDisplay").combobox('select',1);//可使用的 
				$('#editEmbedUrl').attr('disabled',false);
				$("#editNotifyDisplay").combobox({disabled: false}); 
				$('#editEmbedW').attr('disabled',false);
				$('#editEmbedH').attr('disabled',false);
			} else {
				$("#editNotifyDisplay").combobox('select',0);//可使用的 
				$('#editEmbedUrl').attr('disabled',true);
				$("#editNotifyDisplay").combobox({disabled: true}); 
				$('#editEmbedW').attr('disabled',true);
				$('#editEmbedH').attr('disabled',true);
				$("#editEmbedUrl").val('');
				$("#editEmbedH").val('');
				$("#editEmbedW").val('');
			}
		}
	});
	
	
	$("#editEncrypt").combobox('select',0);
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'新建消息',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	cancelPostData();// 上传图片清除 uploader = null
	initOSS();
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}

//  确认编辑 消息
function doEdit(){
	var stId = $("#editStId").val();//消息ID
	var type = $("#editNotifyUse").combobox('getValue');
	var encrypt = $("#editEncrypt").combobox('getValue');
	var title = $("#editTopicTitle").val();
	var message = $("#editTopicDesc").val();
	var imgUrl = $("#topicImg").val();
	var Url = $("#editTopicUrl").val();
	var start_time = $("#queryDateStartEdit").datebox('getValue');
	var end_time = $("#queryDateEndEdit").datebox('getValue');
	var chkFreq = $("#editTopicChkFreq").val();
	
	var embedUrl = $("#editEmbedUrl").val();
	var embedUrlW = $("#editEmbedW").val();
	var embedUrlH = $("#editEmbedH").val();
	var disPlayVal = $("#editNotifyDisplay").combobox('getValue');
	
	if(Number(type||0)<=0){
		return $.messager.alert('提示信息','请选择消息分类','info');
	}
	if(title && title.length>0&&start_time&&end_time) {
		var url = appPath+"/yjxNotify/addNotify.action";
		var sendData = {
			"yjxNotifyInfo.ntfy_id": stId||"",
			"yjxNotifyInfo.ntfy_type": Number(type),
			"yjxNotifyInfo.title": title || "",
			"yjxNotifyInfo.message": message || "",
			"yjxNotifyInfo.image":imgUrl||"",
			"yjxNotifyInfo.url":Url||"",
			"yjxNotifyInfo.embed_url":embedUrl||"",
			"yjxNotifyInfo.width":embedUrlW||"",
			"yjxNotifyInfo.height":embedUrlH||"",
			"yjxNotifyInfo.disp_type":disPlayVal||"",
			"yjxNotifyInfo.encrypt":encrypt||0,
			"yjxNotifyInfo.start_time":start_time||"",
			"yjxNotifyInfo.end_time":end_time||"",
			"yjxNotifyInfo.chk_freq":Number(chkFreq||'0')||0
		};
		
	    $.post(url, sendData, function(data){  
			if (data == "ok") { 
				$.messager.alert('提示信息','提交成功','info');
				$('#editDlg').window('close');
				doQuery();
	        } else {
	        	$.messager.alert('提示信息','提交失败','info');
	        }
	    });
	    
	}else{
		$.messager.alert('提示信息','标题名称、有效起始、截止日期时间是否填写','info');
	}
	
}

//	删除消息内容
function delNotify(){
	var selectItem=$("#tmplGrid").datagrid("getChecked");//获取勾选框
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择项目！','warning');
		return;
	}
	
	$.messager.confirm("确认", "是否确认[删除]所选项目?</span>",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.ntfy_id + ",";
				});
				var url = appPath+"/yjxNotify/delNotify.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}


/* 
 *  一键秀 轮播图 的的显示顺序
 */
function editNotifyOrder(id,number){
	$("#notifyId").val(id);
	$("#notify").val(number);
	
	$("#notifyBtn").show();
	$('#notifyDlg').window({
		title:'显示顺序设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#notifyDlg').window('move',{top:20,left:20});
	$('#notifyDlg').window('open');
}


/* 	
 * 修改显示顺序
 */
function doUpdNotify(){
	var id = $("#notifyId").val();
	var number = $("#notify").val();
	if(!number || number.length == 0 || Number(number)>999 || Number(number)<=0){
		$.messager.alert('提示信息','有效数值范围为：1～999','warning');
		return;
	}
	
	var url = appPath+"/yjxNotify/updNotifyOrder.action?orderid="+id+"&number="+number;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','显示顺序已更新！','info',function(){
				doQuery();
				$('#notifyDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','显示顺序更新失败！','warning');
		}
	});
}

function cancelUpdNotify(){
	$('#notifyDlg').window('close');
}

function cancelEdit(){
	$('#editDlg').window('close');
}

//查询参数条件
function getQueryParam(){
    
	var queryObject = {};
	var findDtS = $("#queryDateStart").datebox('getValue');// 获取开始结束日期
	var findDtE = $("#queryDateEnd").datebox('getValue');
	var findType= $("#editNotifyType").combobox('getValue');// 获取类型	
	
	var findTitleName=$("#queryTitleName").val().trim();// 标题名字
	var findValid = $("#queryNotifyState").combobox('getValue');// 消息状态

	if(findType && Number(findType||'0')>0) queryObject.findNotifyType = findType;// 类型
	if(findTitleName&&findTitleName.length>0) queryObject.findTitleName = findTitleName;// 样版名称
	if(findDtS && findDtS.length>0) queryObject.findDateStart = findDtS+' 00:00:00 ';
	if(findDtE && findDtE.length>0) queryObject.findDateEnd = findDtE+' 23:59:59 ';
	if (findValid && Number(findValid)>0) queryObject.findValid = findValid;
	return queryObject;
}


function getQueryParam2(){
	var queryObject = {};
	var notify_id=$("#notifyId").val();
	if(notify_id && Number(notify_id||'0')>0) queryObject.notify_id = notify_id;// 类型
	return queryObject;
}


/* 
 * 查询数据
 */
function doQuery(){
	$("#tmplGrid").datagrid('unselectAll');
	$("#tmplGrid").datagrid('load',getQueryParam());
}


// ************************ for oss upload image ************************
//******************************** 上传图片 *******************************
var myDomain = 'http://7xogoq.com1.z0.glb.clouddn.com';
var ossDmain = "http://itbour-back.oss-cn-hangzhou.aliyuncs.com/";
var validFile = false;
var uploader = null;

// 图像缩放
function DrawImage(ImgD,FitWidth,FitHeight){
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.height>0){
        if(image.width/image.height>= FitWidth/FitHeight){
            if(image.width>FitWidth){
                ImgD.width=FitWidth;
                ImgD.height=(image.height*FitWidth)/image.width;
            }else{
                ImgD.width=image.width; 
               ImgD.height=image.height;
            }
        } else{
            if(image.height>FitHeight){
                ImgD.height=FitHeight;
                ImgD.width=(image.width*FitHeight)/image.height;
            }else{
                ImgD.width=image.width; 
               ImgD.height=image.height;
            } 
       }
    }
}

function isImage(url) {
    var res, suffix = "";
    var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;

    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = imageSuffixes.length; i < l; i++) {
        if (suffix === imageSuffixes[i]) {
            return true;
        }
    }
    return false;
}

function doPostData(){// 开始上传
	if (validFile && uploader) {
		uploader.start();
	} else {
		setMsg("red", "请选择图像文件！");
	}
}

function cancelPostData(){ // 取消上传
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
}

function setMsg(color, msg) {
	$.messager.alert('提示信息',msg,'info');
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

function fmtHotFlag(value, rowData, rowIndex){
	if(rowData.hotFlag==1)return "是";
	return "否";
}





// ############### FOR OSS UPLOAD START ###############
//var accessid= '';
//var accesskey= '';
//var uploadHost = 'http://itbour-back.oss-cn-hangzhou.aliyuncs.com';
var g_object_name = '';
var dtNow = Date.parse(new Date()); //Date.parse(new Date())/1000;
//var policyText = {
//"expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
//"conditions": [
//  ["content-length-range", 0, 104857600] // 设置上传文件的大小限制
//]
//};
//var policyJsonStr = JSON.stringify(policyText);
//var policyBase64 = Base64.encode(policyJsonStr);
//var message = policyBase64;
//var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true });
//var signature = Crypto.util.bytesToBase64(bytes);

var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
    }
	return str;
}

function getSuffix(filename) {
    var pos = filename.lastIndexOf('.');
    var suffix = '';
    if (pos != -1) {
        suffix = filename.substring(pos);
    }
    return suffix;
}

function calculate_object_name(filename) {
	if (g_object_name){
		g_object_name = '';
	}
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
    g_object_name = "image/U"+g_userId+"/"+nowStr + randomString(20);
}

function set_upload_param(up, filename, ret) {
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date());//  Date.parse(new Date())/1000
	OSS_PARAM.flg = false;
    if (OSS_PARAM.expire < dtNow + 5000) {// 5s
    	var url = appPath+"/itbImg/getOSSToken.action";
        $.get(url, function(data){  
    		if (data && data.signature) { 
    			OSS_PARAM.expire = data.expire;
    			OSS_PARAM.uploadHost = data.uploadHost;
    			OSS_PARAM.accessKeyId = data.accessKeyId;
    			OSS_PARAM.policyBase64 = data.policyBase64;
    			OSS_PARAM.signature = data.signature;
    			OSS_PARAM.flg = true;
    			
    			doUpStart(up, filename, ret);
            } else {
            	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
            }  
        });
    } else {
    	doUpStart(up, filename, ret);
    }
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
        calculate_object_name(filename);
    }
    var new_multipart_params = {
        'key' : g_object_name,
        'policy': OSS_PARAM.policyBase64,
        'OSSAccessKeyId': OSS_PARAM.accessKeyId, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': OSS_PARAM.signature,
    };

    up.setOption({
        'url': OSS_PARAM.uploadHost,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function clearUploadList() {
	$("#topicImg").html('');
	$("#topicImg").val('');
}

function initOSS() {
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}

	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selImgFile', 
	    //multi_selection: false,
		//container: document.getElementById('container'),
		//flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		//silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',
		init: {
			PostInit: function() {// 当Init事件发生后触发
//				document.getElementById('upImgFile').onclick = function() {
//		            set_upload_param(uploader, '', false);
//		            return false;
//				};
			},

			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bAllOk = true;
				plupload.each(files, function(file) {
					if (isImage(file.name)) {
						// add file info list
						set_upload_param(uploader, '', false);
				        return false;
					} else {
						bAllOk = false;
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					}
				});
				
				if (!bAllOk) {
					setMsg("red", "已过滤非图像文件！");
				}     
			},

			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },

			UploadProgress: function(up, file) {
				// TODO
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	console.log(g_object_name);
	            	var showImg = '';
	            	var tmp = ossDmain+g_object_name
	    			if(g_object_name && g_object_name.length>0) {
	    				showImg = tmp+'?x-oss-process=image/resize,m_pad,h_150,w_150,color_cccccc';
	    			}
	    			var imgHtml = '<img src="'+showImg+'" style="display:inline;max-height:100px;max-width:200px">';
	    			$("#topicImg").append(imgHtml).val(tmp||'');
	            }
	            else {
	            	setMsg("red", '上传出错！');
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
	            }
			},

			Error: function(up, err) {
//				document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
				setMsg("red", err.response);
			}
		}
	});
	
	uploader.init();
}
//############### FOR OSS UPLOAD END ###############
